package de.lulusoft.anothertorrent.gui.views.Providers;

import java.util.ArrayList;

import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;

import de.lulusoft.anothertorrent.core.servers.Server;
import de.lulusoft.anothertorrent.gui.AnotherTorrentGui;
import de.lulusoft.anothertorrent.gui.exceptions.ExceptionHandler;
import de.lulusoft.anothertorrent.gui.preferences.PreferenceConstants;

public class OverviewViewContentProvider implements ITreeContentProvider {

	@Override
	public Object[] getChildren(Object parentElement) {
		return getElements(parentElement);
	}

	@Override
	public Object getParent(Object element) {
		return null;
	}

	@Override
	public boolean hasChildren(Object element) {
		if (element instanceof Server)
		{
			Object[] os;
			try {
				os = ((Server)element).getRTorrentManager().getViewNames().toArray();
			
				ArrayList<String> retval = new ArrayList<String>();
				// Ignore views
				for (Object o : os)
				{
					if (o instanceof String)
					{
						String viewName = (String) o;
						String[] ignoredViews = AnotherTorrentGui.getDefault()
							.getPreferenceStore().getString(PreferenceConstants.P_IGNORE_VIEWS)
							.split(",");
						boolean found = false;
						for (String view : ignoredViews)
						{
							if (view.trim().equals(viewName))
								found = true;
						}
						if (!found)
							retval.add(viewName);
					}
				}
				return !retval.isEmpty();
			} catch (Exception e) {
				ExceptionHandler.alert("Could not fetch Children for Overview View", e);
			}
		}
		return false;
	}

	@Override
	public Object[] getElements(Object inputElement) {
		
		if (inputElement instanceof Server)
		{
			Object[] os;
			try {
				os = ((Server)inputElement).getRTorrentManager().getViewNames().toArray();
			
				ArrayList<String> retval = new ArrayList<String>();
				// Ignore views
				for (Object o : os)
				{
					if (o instanceof String)
					{
						String viewName = (String) o;
						String[] ignoredViews = AnotherTorrentGui.getDefault()
							.getPreferenceStore().getString(PreferenceConstants.P_IGNORE_VIEWS)
							.split(",");
						boolean found = false;
						for (String view : ignoredViews)
						{
							if (view.trim().equals(viewName))
								found = true;
						}
						if (!found)
							retval.add(viewName);
					}
				}
				return retval.toArray();
			} catch (Exception e) {
				ExceptionHandler.alert("Could not fetch Children for Overview View", e);
			}
			
		}
		return null;
	}

	@Override
	public void dispose() {
	}

	@Override
	public void inputChanged(Viewer viewer, Object oldInput,
			Object newInput) {
	}

}
